<template>
	<view class="uni-container">
		<uni-forms ref="form" :model="formData" validate-trigger="submit" err-show-type="toast" :label-width="90">
			<uni-forms-item name="store_name" label="门店名称">
				<uni-easyinput placeholder="门店名称" v-model="formData.store_name"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item label="门店位置">
				<view class="input-border" @click="openCL">
					<view v-if="formData.store_tencent_latitude">
						{{formData.store_tencent_latitude}},{{formData.store_tencent_longitude}}
					</view>
					<view v-else>
						请选择
					</view>
				</view>
			</uni-forms-item>
			<uni-forms-item name="store_address" label="详细位置">
				<uni-easyinput placeholder="请输入详细地址" v-model="formData.store_address"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="bs_weixin_no" label="微信商户号">
				<uni-easyinput placeholder="用于实时收款的官方账号" v-model="formData.bs_weixin_no"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="bs_alipay_no" label="支付宝商户号">
				<uni-easyinput placeholder="用于实时收款的官方账号" v-model="formData.bs_alipay_no"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="auth_serial_no" label="授权序列号">
				<uni-easyinput placeholder="授权序列号" v-model="formData.auth_serial_no"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="store_head_image" label="上传门头照">
				<!-- <uni-file-picker :auto-upload="false" limit="1" v-model="imageValue" style="color:grey" disable-preview
					fileMediatype="image" :imageStyles="imageStyles" mode="grid" @select="selectPic" @progress="progress"
					@success="success" @fail="fail" /> -->
				<uni-file-picker :auto-upload="false" limit="1" style="color:grey" :del-icon="false" disable-preview
					file-mediatype="image" @select="selectPic" @progress="progress" @success="success">
					<!-- <image @error="imageError" v-if="formData.store_head_image" style="width: 52px;height: 52px;"
						:src="picServiceUrl+formData.store_head_image" mode="">
					</image> -->
					<image v-if="formData.store_head_image" style="width: 52px;height: 52px;" mode="widthFix"
						:data-src="picServiceUrl+formData.store_head_image"
						:src="picServiceUrl+formData.store_head_image">
					</image>
					<view v-else>
						选择
					</view>
				</uni-file-picker>
			</uni-forms-item>
			<uni-forms-item name="industry" label="行业">
				<uni-data-picker v-model="formData.industry" v-slot:default="{data, error, options}" :clear-icon="false"
					:localdata="hangyeRange" popup-title="请选择" @change="hangyeChange">
					<view v-if="error" class="error input-border">
						<text>{{error}}</text>
					</view>
					<view v-else-if="data.length" class="selected input-border">
						<text>{{data[0].text}} - {{data[1].text}}</text>
					</view>
					<!-- <view v-else-if="formData.industry" class="input-border">
						<text>{{formData.industry[0].text}} - {{formData.industry[1].text}}</text>
					</view> -->
					<view v-else class="input-border">
						<text>请选择</text>
					</view>
				</uni-data-picker>
			</uni-forms-item>
			<uni-forms-item name="bs_open_hour_start" label="营业时间">
				<view class="pick-time">
					<picker mode="time" class="picker" :value="startTime" @change="bindChange" data-name="startTime">
						<view>{{startTime?startTime:"请选择"}}</view>
					</picker>
					<view class="fenge">
						至
					</view>
					<picker mode="time" class="picker" :value="endTime" @change="bindChange" data-name="endTime">
						<view>{{endTime?endTime:"请选择"}}</view>
					</picker>
				</view>
			</uni-forms-item>

			<uni-forms-item name="plat_discount" label="结算折扣">
				<!-- <uni-easyinput placeholder="最少75折" type="number" v-model="formData.plat_discount"></uni-easyinput> -->
				<uni-data-picker v-model="formData.plat_discount" :localdata="huiyuanRange" popup-title="请选择折扣">
					<view class="member-discount" v-if="formData.plat_discount==100">
						无折扣
					</view>
					<view class="member-discount" v-else-if="formData.plat_discount">
						{{formData.plat_discount/10+"折"}}
					</view>
					<view class="member-discount" v-else>
						请选择
					</view>
				</uni-data-picker>
			</uni-forms-item>
			<uni-forms-item name="wifi_name" label="WIFI账号">
				<uni-easyinput placeholder="WIFI账号" v-model="formData.wifi_name"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="wifi_password" label="WIFI密码">
				<uni-easyinput placeholder="WIFI密码" v-model="formData.wifi_password"></uni-easyinput>
			</uni-forms-item>
			<label class="agreement" v-if="!isEdit">
				<u-checkbox-group @change="clickAgreement">
					<!-- <radio @click="clickAgreement" class="my-radio" :checked="isAgreement" ></radio> -->
					<u-checkbox class="my-radio" v-model="isAgreement" shape="circle" label="已阅读并同意"></u-checkbox>
				</u-checkbox-group>
				<text @click.stop="goAgreement">《在花一商户服务协议》</text>
			</label>
			<view class="uni-button-group">
				<button type="primary" class="uni-button" style="background-color: #0e100e;" @click="submit">提交</button>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	import {
		nanoid
	} from 'nanoid/non-secure'
	import OptionJson from "../../utils/optionJson.js"
	import uQRCode from '@/uni_modules/Sansnn-uQRCode/js_sdk/uqrcode/uqrcode.js'
	const app = getApp();

	/* import {
		validator
	} from '../../js_sdk/validator/zhy_business_info.js'; */

	const db = uniCloud.database();
	const dbCollectionName = 'zhy_business_info';

	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.indexOf(key) > -1) {
				result[key] = validator[key]
			}
		}
		return result
	}

	export default {
		data() {
			let formData = {
				offlineBusinessId: "",
				store_address_province: "",
				store_address_city: "",
				store_tencent_latitude: "",
				store_tencent_longitude: "",
				store_address: "",
				store_name: "",
				bs_weixin_no: "",
				bs_alipay_no: "",
				auth_serial_no: "",
				store_head_image: "",
				industry: [],
				bs_open_hour_start: "",
				bs_open_hour_end: "",
				plat_discount: null,
				create_wx_openid: null,
				create_alipay_openid: null,
				join_platform_guarantee_plan: 0,
				store_address_province: '',
				store_address_city: '',
				reverse_amount: 0,
			}
			return {
				formData,
				formOptions: {},
				/* rules: {
					...getValidator(Object.keys(formData))
				}, */
				hangyeRange: [],
				huiyuanRange: [],
				startTime: "",
				endTime: "",
				isAgreement: false,
				picServiceUrl: app.globalData.picServiceUrl,
				businessUploadFileDir: app.globalData.businessUploadFileDir,
				// 是否为修改
				isEdit: false,
				formId: null,
				isLogin: false,
				timer: null,
			}
		},
		async onLoad(e) {
			uni.showLoading({
				mask: true
			})
			this.picServiceUrl = app.globalData.picServiceUrl
			this.businessUploadFileDir = app.globalData.businessUploadFileDir;
			if (e && e.id) {
				this.formData.offline_business_id = e.id
				// this.formData.promoter_id = e.sharid
				// this.formData.distribution_rate = e.rate
			}
			this.hangyeRange = OptionJson.jylmJson;
			console.log(this.hangyeRange);

			// 折扣优惠
			let hr = [];
			for (let i = 1; i <= 75; i++) {
				hr.push({
					"value": i,
					"text": i / 10 + '折',
				})
			}
			this.huiyuanRange = hr;

			/* //#ifdef  MP-ALIPAY
			uni.showModal({
				content: '请用微信扫码填写',
				showCancel: false,
				confirmText: '好的',
				confirmColor: '#333',
				success: function(res) {
					uni.navigateBack({
						delta: 1
					})
				},
				fail: function(res) {}
			})
			// #endif */

			/* uni.showLoading({
				mask: true
			}) */
			console.log('1111111111');
			console.log(this.$logintool.isLogin());
			if (!this.$logintool.isLogin()) {
				console.log('未登录');
				let res = await this.$logintool.login()
				if (res) {
					console.log('登录完成：' + JSON.stringify(res));
					// 登录成功
					this.setUserInfo()
					uni.hideLoading()
				}
			} else {
				// 直接设置值
				this.setUserInfo()
			}
			uni.hideLoading()
		},
		onShow() {

		},
		onReady() {
			// this.$refs.form.setRules(this.rules)
		},
		methods: {
			reload() {
				uni.reLaunch({
					url: '/pages/zhy_business_info/addOrEdit'
				})
				/* // 页面重载
				const pages = getCurrentPages()
				// 声明一个pages使用getCurrentPages方法
				const curPage = pages[pages.length - 1]
				// 声明一个当前页面
				curPage.onLoad(curPage.options) // 传入参数
				curPage.onShow()
				curPage.onReady()
				// 执行刷新 */
			},
			// 赋给当前用户赋值
			setUserInfo() {
				// #ifdef MP-WEIXIN
				this.formData.create_wx_openid = uni.getStorageSync(app.globalData.session.userKey)
				// #endif
				// #ifdef MP-ALIPAY
				this.formData.create_alipay_openid = uni.getStorageSync(app.globalData.session.userKey)
				// #endif

				this.isLogin = this.$logintool.isLogin()
				let userType = uni.getStorageSync(app.globalData.session.userType);
				if (userType == 1) {
					// 普通用户，新增商户信息
					this.isEdit = false
					console.log('this.formData.offlineBusinessId::::' + this.formData.offlineBusinessId);
					this.formData.offlineBusinessId = this.generateOffBusinessId()
					console.log('新增：offlineBusinessId' + this.formData.offlineBusinessId);
				} else if (userType == 2) {
					this.formData = uni.getStorageSync(app.globalData.session.businessInfo);
					// 修改商户信息
					this.isEdit = true
					this.formData = uni.getStorageSync(app.globalData.session.businessInfo);
					this.startTime = this.formData.bs_open_hour_start;
					this.endTime = this.formData.bs_open_hour_end;
					this.formId = this.formData._id
					this.formData._id = null
					console.log('this.formId:' + this.formId);
				}
			},
			generateOffBusinessId() {
				return 'bs' + nanoid(8)
			},
			openCL() {
				let that = this
				uni.getLocation({
					success(res1) {
						console.log('当前位置:');
						console.log(JSON.stringify(res1));
						uni.chooseLocation({
							latitude: res1.latitude,
							longitude: res1.longitude,
							title: '所在位置',
							success: (res) => {
								console.log(JSON.stringify(res));
								if (res.provinceName) {
									that.formData.store_address_province = res.provinceName;
								}
								if (res.cityName) {
									that.formData.store_address_city = res.cityName;
								}
								that.formData.store_address = res.address;
								that.formData.store_tencent_latitude = res.latitude;
								that.formData.store_tencent_longitude = res.longitude;
							}
						});
					}
				})

			},
			// 上传成功
			success(e) {
				console.log('上传成功', e)
			},
			// 上传失败
			fail(e) {
				console.log('上传失败：', e)
			},
			// 获取上传进度
			progress(e) {
				console.log('上传进度：', e)
			},
			selectPic(res) {
				this.uploadFun(res.tempFiles[0])
			},
			// 文件上传：商户的文件存储在cloudstorage/
			uploadFun(item) {
				let that = this
				if (item == undefined) {
					// 未上传
					return
				}
				console.log('上传对象:' + JSON.stringify(item));
				// 使用随机字符，防止多次上传同一个导致失败
				let objName = app.globalData.fileRootDir + '/' + this.businessUploadFileDir + '/' +
					this.getNowFormatDate() + '/bs' + nanoid(5) + item.name
				uniCloud.uploadFile({
					filePath: item.path,
					cloudPathAsRealPath: true,
					cloudPath: objName,
					onUploadProgress: function(progressEvent) {
						console.log(progressEvent);
						var percentCompleted = Math.round(
							(progressEvent.loaded * 100) / progressEvent.total
						);
					},
					success(res) {
						console.log('上传成功！' + JSON.stringify(res))
						console.log('上传成功！' + JSON.stringify(that.formData))
						// that.formData.store_head_image = res.fileID;
						that.formData.store_head_image = objName;
					},
					fail(res) {
						console.log('上传失败！' + JSON.stringify(res))
					},
					complete(res) {
						console.log('上传完成！' + JSON.stringify(res))
					}
				});
			},
			getFileName(filePath) {
				if (filePath) {
					return filePath.split("/").pop();
				}
				return null;
			},
			//获取当前日期函数
			getNowFormatDate() {
				let date = new Date(),
					year = date.getFullYear(), //获取完整的年份(4位)
					month = date.getMonth() + 1, //获取当前月份(0-11,0代表1月)
					strDate = date.getDate() // 获取当前日(1-31)
				if (month < 10) month = `0${month}` // 如果月份是个位数，在前面补0
				if (strDate < 10) strDate = `0${strDate}` // 如果日是个位数，在前面补0
				return `${year}-${month}-${strDate}`
			},

			bindChange(e) {
				let name = e.currentTarget.dataset.name;
				let value = e.detail.value
				this[name] = value;
			},
			hangyeChange(e) {
				console.log("行业切换：" + JSON.stringify(e));
				this.formData.industry = e.detail.value
			},
			clickAgreement(e) {
				this.isAgreement = !this.isAgreement
				console.log(this.isAgreement);
			},
			/**
			 * 验证表单并提交
			 */
			submit() {
				let form = this.formData;
				form.bs_open_hour_start = this.startTime;
				form.bs_open_hour_end = this.endTime;
				if (!this.formData.store_name) {
					return uni.showToast({
						title: "请输入门店名称",
						icon: "none"
					})
				}
				if (!this.formData.store_tencent_latitude) {
					return uni.showToast({
						title: "请选择门店位置",
						icon: "none"
					})
				}
				if (!this.formData.store_address) {
					return uni.showToast({
						title: "请输入详细地址",
						icon: "none"
					})
				}
				if (!this.formData.store_head_image) {
					return uni.showToast({
						title: "请选择门头照",
						icon: "none"
					})
				}
				if (!this.formData.industry.length) {
					return uni.showToast({
						title: "请选择行业",
						icon: "none"
					})
				}
				if (!this.formData.bs_open_hour_start) {
					return uni.showToast({
						title: "请选择开始营业时间",
						icon: "none"
					})
				}
				if (!this.formData.bs_open_hour_end) {
					return uni.showToast({
						title: "请选择结束营业时间",
						icon: "none"
					})
				}

				if (!this.formData.plat_discount) {
					return uni.showToast({
						title: "请选择折扣",
						icon: "none"
					})
				}
				if (!this.isEdit) {
					if (!this.isAgreement) {
						return uni.showToast({
							title: "请阅读并同意协议",
							icon: "none"
						})
					}
				}
				console.log(JSON.stringify(this.formData));
				uni.showLoading({
					mask: true
				})
				try {
					this.submitForm(this.formData)
					uni.hideLoading()
				} catch (e) {
					console.log('submitForm err:' + e);
					uni.hideLoading()
				}
				/* this.$refs.form.validate().then((res) => {
					return this.submitForm(res)
				}).catch(() => {}).finally(() => {
					uni.hideLoading()
				}) */
			},

			/**
			 * 提交表单
			 */
			submitForm(value) {
				// 使用 clientDB 提交数据
				let that = this
				// 使用云函数：查询/修改/新增
				if (this.isEdit) {
					// 修改
					const {
						_id,
						...updateData
					} = value;
					updateData.update_time = Date.now();
					console.log('修改111');
					console.log(JSON.stringify(value));
					uniCloud.callFunction({
						name: 'zhy-business-info-crud',
						data: {
							crud: app.globalData.crud.update,
							formId: that.formId,
							data: updateData
						},
						success: (res) => {
							uni.showToast({
								icon: 'none',
								title: '修改成功'
							})
							console.log('that:' + JSON.stringify(that.formData));
							// that.getOpenerEventChannel().emit('refreshData')
							// 重新登录再刷新页面
							this.$logintool.logout()
							this.timer = setTimeout(() => {
								this.reload()
							}, 500)
						},
						fail(err) {
							console.log('22233333');
							uni.showModal({
								content: err.message || '请求服务失败',
								showCancel: false
							})
						}
					})
				} else {
					value.update_time = Date.now();
					value.create_time = Date.now();
					uniCloud.callFunction({
						name: 'zhy-business-info-crud',
						data: {
							crud: app.globalData.crud.add,
							data: value
						},
						success: (res) => {
							uni.showToast({
								icon: 'none',
								title: '入驻成功'
							})
							// this.getOpenerEventChannel().emit('refreshData')
							this.$logintool.logout()
							this.timer = setTimeout(() => {
								// 重新登录再刷新页面
								this.reload()
								// 添加分账商户
								this.$zhyPay.profitsharingaddreceiver(uni.getStorageSync(app.globalData.session.businessInfo.offlineBusinessId))
							}, 500)
						},
						fail(err) {
							console.log(6666666666);
							uni.showModal({
								content: err.message || '请求服务失败',
								showCancel: false
							})
						}
					})
					/* return db.collection(dbCollectionName).add(value).then((res) => {
						uni.showToast({
							icon: 'none',
							title: '入驻成功'
						})
						this.getOpenerEventChannel().emit('refreshData')
						setTimeout(() => uni.navigateBack(), 500)
					}).catch((err) => {
						console.log(6666666666);
						uni.showModal({
							content: err.message || '请求服务失败',
							showCancel: false
						})
					}) */
				}
			},
			goAgreement() {
				console.log('跳转...');
				uni.navigateTo({
					url: "/pages/agreement/index?name=在花一商户服务协议.txt",
					success(res) {

					},
					fail(res) {
						console.log('跳转...失败：' + JSON.stringify(res));
					}
				})
			},
			imageError(e) {
				console.log('图片展示异常:' + JSON.stringify(e));
			}
		},
		onUnload() {
			if (this.timer) {
				clearInterval(this.timer)
				clearTimeout(this.timer)
				this.timer = null
			}
		}
	}
</script>

<style lang="scss">
	.uni-container {
		padding: 15px;
	}

	.uni-input-border,
	.uni-textarea-border {
		width: 100%;
		font-size: 14px;
		color: #666;
		border: 1px #e5e5e5 solid;
		border-radius: 5px;
		box-sizing: border-box;
	}

	.uni-input-border {
		padding: 0 10px;
		height: 35px;

	}

	.uni-textarea-border {
		padding: 10px;
		height: 80px;
	}

	.uni-button-group {
		margin-top: 10px;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		justify-content: center;
	}

	.uni-button {
		width: 184px;
	}

	.uniui-location-filled ::v-deep {
		font-size: 25px !important;
	}

	.member-discount {
		line-height: 36px;
	}

	.eidt-button {
		width: 50%;
		margin: 30px auto;
	}

	.title {
		margin: 15px 0;
		color: #000;
		text-align: center;
	}

	.item-bg {
		background-color: #f2f3f8;
		padding: 10px 0;
		min-height: 80vh;
	}

	.canvas-position {
		position: absolute;
		top: -1000px;
	}

	.item_border {
		margin: 15px;
		padding: 15px 15px;
		border-radius: 15px;
		box-shadow: 0px 3px 5px 0px rgba(207, 207, 207, 0.39);
		background-color: white;
		color: #666;
	}

	.code-canvas {
		position: absolute;
		top: -1000px;
	}

	.my-forms {
		padding: 10px;
		margin: 10px 0;
	}

	.pick-time {
		display: flex;
		align-items: center;
		color: grey;

		.fenge {
			width: 20%;
			text-align: center;
		}

		.picker {
			border: 1px solid #e5e5e5;
			border-radius: 4px;
			font-size: 14px;
			padding: 8px 10px;
			width: 40%;

		}

	}

	.input-border {
		flex: 1 1 0;
		border: 1px solid #e5e5e5;
		border-radius: 4px;
		font-size: 14px;
		color: grey;
		padding: 8px 10px;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.select-pic {
		min-height: 36px;
		line-height: 38px;
		padding: 0 10px;
		border: 1px solid #e5e5e5;
		width: 100px;
		text-align: center;
	}

	.ok-msg {
		height: 100px;
		line-height: 100px;
		text-align: center;
		margin-bottom: 20px;
		font-size: 20px;
	}

	.input-value {
		padding: 0 10px !important;
	}

	.agreement {
		font-size: 14px;
		color: #666666;
		display: flex;
		align-items: center;
		padding: 10px;

		.my-radio {
			transform: scale(0.7, 0.7)
		}

		text {
			text-decoration: underline;
		}
	}
</style>